<template>
	<view class="u-m-l-30 u-m-r-30 u-m-b-50 body">
		<u-sticky>
			<view class="sticky">
				<view class="u-flex u-flex-1 u-row-left u-col-center" @click="showSelectClick">
					<u-icon name="https://account-book-cos.1900shop.online/static/images/index/book.png"
						size="36"></u-icon>
					<text class="u-m-l-6 u-m-r-10 u-font-bold u-font-30">{{selectBook.bookName || '请选择账本'}}</text>
					<u-icon name="arrow-down" size="24"></u-icon>
				</view>
				<view class="u-flex u-row-center u-m-t-30">
					<u-subsection class="subsection-style" :list=" list" :current="sectionIndex" active-color="#19be6b"
						font-size="25" height="60" @change="sectionChange"></u-subsection>
				</view>
				<view>
					<view class="u-flex u-row-center u-m-t-30 u-font-15">
						<u-icon class="u-m-r-30" v-if="subtractEnableOrNot"
							name="https://account-book-cos.1900shop.online/static/images/statistics/左移.png"
							color="#000000" size="38" @click="reduceDate"></u-icon>
						<text>{{startDateValue||'全部账单'}}</text>
						<u-icon v-if="endDateValue"
							name="https://account-book-cos.1900shop.online/static/images/statistics/波浪号.png"
							color="#000000" size="38"></u-icon>
						<text>{{endDateValue}}</text>
						<u-icon class="u-m-l-30" v-if="addEnableOrNot"
							name="https://account-book-cos.1900shop.online/static/images/statistics/右移.png"
							color="#000000" size="38" @click="addDate"></u-icon>
						<u-icon class="u-m-l-30" v-if="notAddEnableOrNot"
							name="https://account-book-cos.1900shop.online/static/images/statistics/右移置灰.png"
							color="#000000" size="38"></u-icon>
					</view>
					<view class="u-flex u-row-right">
						<u-icon name="https://account-book-cos.1900shop.online/static/images/statistics/筛选.png"
							color="#000000" size="38" @click="selectDate"></u-icon>
						<u-calendar v-model="showDate" mode="range" active-bg-color="#19be6b" range-color="#ffffff"
							btn-type="success" range-bg-color="#18b566" @change="change">
						</u-calendar>
					</view>
				</view>
			</view>
		</u-sticky>
		<view class="u-p-10 u-bg u-m-t-20">
			<view class="u-flex">
				<view class="">
					<u-icon name="https://account-book-cos.1900shop.online/static/images/statistics/总览.png"
						size="60"></u-icon>
				</view>
				<view class="u-m-l-20 u-font-15">
					收支总览
				</view>
			</view>
			<view class="u-flex u-row-between u-m-t-30">
				<view class="u-flex-wrap">
					<view class="u-font-5 u-text-center">
						支出
					</view>
					<view class="u-m-t-30 u-font-15">
						<u-icon size="30"
							name="https://account-book-cos.1900shop.online/static/images/statistics/人民币.png"></u-icon>
						{{statisticsTotalData.selectExpenditure ? Number(statisticsTotalData.selectExpenditure).toFixed(2) : '0.00'}}
					</view>
				</view>
				<view class="u-flex-wrap">
					<view class="u-font-5 u-text-center">
						收入
					</view>
					<view class="u-m-t-30 u-font-15">
						<u-icon size="30"
							name="https://account-book-cos.1900shop.online/static/images/statistics/人民币.png"></u-icon>
						{{statisticsTotalData.selectIncome ? Number(statisticsTotalData.selectIncome).toFixed(2) : '0.00'}}
					</view>
				</view>
				<view class="u-flex-wrap">
					<view class="u-font-5 u-text-center">
						总笔数
					</view>
					<view class="u-m-t-30 u-font-15">
						<u-icon size="30"
							name="https://account-book-cos.1900shop.online/static/images/statistics/人民币.png"></u-icon>
						{{statisticsTotalData.bookkeepingNum ?statisticsTotalData.bookkeepingNum:'0'}}
					</view>
				</view>
			</view>
		</view>
		<view class="u-p-10 u-bg u-m-t-20" v-if="isChartShow">
			<view class="u-flex u-flex-nowrap">
				<view class="">
					<u-icon name="https://account-book-cos.1900shop.online/static/images/statistics/折线图.png"
						size="60"></u-icon>
				</view>
				<view class="u-m-l-20 u-font-15">{{incOrExpName}}趋势</view>
				<view class="u-m-l-70" v-if="isEnableOrNotAreaCharts">
					<u-icon name="https://account-book-cos.1900shop.online/static/images/statistics/柱状图.png" size="40"
						@click="toggleColumn"></u-icon>
				</view>
				<view class="u-m-l-70" v-if="isEnableOrNotColumnCharts">
					<u-icon name="https://account-book-cos.1900shop.online/static/images/statistics/折线图-new.png"
						size="40" @click="toggleArea"></u-icon>
				</view>
			</view>
			<view class="charts-box" v-if="isEnableOrNotAreaCharts">
				<qiun-data-charts :ontouch="true" background="#ffffff" type="area" loadingType="5" :canvas2d="true"
					:opts="opts" :chartData="chartData" tooltipFormat="lineCharts" />
			</view>
			<view class="charts-box" v-if="isEnableOrNotColumnCharts">
				<qiun-data-charts :ontouch="true" background="#ffffff" type="column" loadingType="5" :canvas2d="true"
					:opts="columnOpts" :chartData="chartData" tooltipFormat="lineCharts" />
			</view>
			<view class="u-flex u-row-center u-m-t-20">
				<u-subsection class="toggle-subsection-style" :list="toggleList" :current="type" active-color="#19be6b"
					font-size="20" height="50" @change="toggleChange"></u-subsection>
			</view>
		</view>
		<view class="u-p-10 u-bg u-m-t-20">
			<view class="u-flex u-flex-nowrap">
				<view class="">
					<u-icon name="https://account-book-cos.1900shop.online/static/images/statistics/汇总.png"
						size="60"></u-icon>
				</view>
				<view class="u-m-l-20 u-font-15">{{changeName}}账单汇总</view>
			</view>
			<view class="">
				<u-table border-color="#18b566">
					<u-tr>
						<u-th>日期</u-th>
						<u-th>收入</u-th>
						<u-th>支出</u-th>
					</u-tr>
					<u-tr>
						<u-td>总计</u-td>
						<u-td>{{getCollectListData.incomeTotal ? Number(getCollectListData.incomeTotal).toFixed(2) : '-'}}</u-td>
						<u-td>{{getCollectListData.expenditureTotal ? Number(getCollectListData.expenditureTotal).toFixed(2) : '-'}}</u-td>
					</u-tr>
					<u-tr>
						<u-td>日均</u-td>
						<u-td>{{getCollectListData.incomeAverage ? Number(getCollectListData.incomeAverage).toFixed(2) : '-'}}</u-td>
						<u-td>{{getCollectListData.expenditureAverage ? Number(getCollectListData.expenditureAverage).toFixed(2) : '-'}}</u-td>
					</u-tr>
					<view v-for="(item,i) in statisticsCollectMoneyListRes" :key="i">
						<u-tr>
							<u-td>{{item.statisticsTime}}</u-td>
							<u-td>{{item.statisticsIncome ? Number(item.statisticsIncome).toFixed(2) : '-'}}</u-td>
							<u-td>{{item.statisticsExpend ? Number(item.statisticsExpend).toFixed(2) : '-'}}</u-td>
						</u-tr>
					</view>
				</u-table>
			</view>
		</view>
		<u-select v-model="showSelect" :list="booksInfo" mode="single-column" :default-value="defaultIndex" title="账本"
			value-name="id" label-name="bookName" @confirm="setBook"></u-select>
	</view>
</template>

<script>
	import moment from '@/components/moment/moment.js';
	var _this;
	let canvaPie = null; //月统计
	let dayPie = null; //日统计
	let incomeCanvasPie = null //月收入统计

	export default {
		data() {
			return {
				list: [{
						name: '总'
					},
					{
						name: '年'
					},
					{
						name: '月'
					},
					{
						name: '周'
					}
				],
				toggleList: [{
						name: '收入'
					},
					{
						name: '支出'
					}
				],
				isChartShow: false,
				showSelect: false,
				subtractEnableOrNot: false,
				addEnableOrNot: false,
				notAddEnableOrNot: false,
				startDateValue: '',
				endDateValue: '',
				sectionIndex: 0,
				defaultIndex: [0],
				ifDefaultIndex: true,
				booksInfo: [],
				type: 1,
				selectBook: '',
				show: false,
				showDate: false,
				mode: 'range',
				isEnableOrNotAreaCharts: true,
				chartData: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['area'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["#18b566", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					fontSize: 10,
					padding: [5, 5, 0, 5],
					enableScroll: true,
					legend: {
						show: false
					},
					xAxis: {
						disableGrid: true,
						fontSize: 5,
						itemCount: 8, //x轴单屏显示数据的数量，默认为5个
						scrollShow: true, //新增是否显示滚动条，默认false
						scrollAlign: 'left', //滚动条初始位置
						scrollBackgroundColor: '#F7F7FF', //默认为 #EFEBEF
						scrollColor: '#DEE7F7', //默认为 #A6A6A6}
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2
					},
					extra: {
						area: {
							type: "curve",
							opacity: 0.2,
							addLine: true,
							width: 2,
							gradient: false,
							activeType: "hollow"
						}
					}
				},
				isEnableOrNotColumnCharts: false,
				columnChartData: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['column'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				columnOpts: {
					color: ["#18b566", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					fontSize: 10,
					padding: [5, 5, 0, 5],
					enableScroll: true,
					legend: {
						show: false
					},
					xAxis: {
						disableGrid: true,
						fontSize: 5,
						itemCount: 8, //x轴单屏显示数据的数量，默认为5个
						scrollShow: true, //新增是否显示滚动条，默认false
						scrollAlign: 'left', //滚动条初始位置
						scrollBackgroundColor: '#F7F7FF', //默认为 #EFEBEF
						scrollColor: '#DEE7F7', //默认为 #A6A6A6}
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2
					},
					extra: {
						column: {
							type: "group",
							width: 10,
							activeBgColor: "#000000",
							activeBgOpacity: 0.08,
							barBorderCircle: true,
							linearType: "custom"
						}
					}
				},
				incOrExpName: "支出",
				changeName: '总',
				bookId: '',
				bookName: '',
				statisticsTotalData: {},
				getCollectListData: {},
				statisticsCollectMoneyListRes: []
			}
		},
		// 页面初次渲染完成了，但是渲染完成了，你才发送请求获取数据，显得有些慢
		onReady() {},
		//只加载一次，监听页面加载，其参数为上个页面传递的数据，参数类型为Object
		onLoad() {
			_this = this;
			_this.startDateValue = '';
		},
		//监听页面显示。页面每次出现都触发，包括从下级页面点返回露出当前页面
		onShow() {
			if (_this.os_books.length > 0 && _this.ifDefaultIndex) {
				_this.bookId = _this.os_books[_this.os_selectbook].id
				_this.bookName = _this.os_books[_this.os_selectbook].bookName
				_this.selectBook = {
					bookId: _this.bookId,
					bookName: _this.bookName
				}
			} else {
				_this.getBook()
			}
			_this.booksInfo = _this.os_books
			if (_this.ifDefaultIndex) {
				_this.defaultIndex[0] = _this.os_selectbook
			}
			_this.reload()
		},
		methods: {
			//点击选择账本
			showSelectClick() {
				_this.showSelect = true
			},
			//获取账本
			async getBook() {
				await _this.$u.api.getBookList().then(res => {
					console.log("获取账本列表信息:" + JSON.stringify(res))
					if (res) {
						_this.$u.vuex('os_books', res)
						res.list.forEach((item, i) => {
							if (item.defaultBook == 1) {
								_this.$u.vuex('os_defbook', i)
							}
						})
						if (_this.os_defbook == -1) {
							_this.bookId = _this.os_books[0].id
							_this.bookName = _this.os_books[0].bookName
						} else {
							_this.bookId = _this.os_books[_this.os_defbook].id
							_this.bookName = _this.os_books[_this.os_defbook].bookName
						}
						_this.selectBook = {
							bookId: _this.bookId,
							bookName: _this.bookName
						}
					} else {
						_this.$u.toast('请先创建账本')
						_this.goTabbarUrl('/pages/app/index')
					}
				})
			},
			//重新加载  总览统计查询，统计-图表统计，统计-获取汇总列表
			reload() {
				_this.statisticsTotal()
				_this.chartStatistics()
				_this.getCollectList();
			},
			//总览统计查询
			async statisticsTotal() {
				await _this.$u.api.statisticsTotal({
					bookId: _this.selectBook.bookId,
					timeType: _this.sectionIndex,
					startTime: _this.startDateValue,
					endTime: _this.endDateValue
				}).then((res) => {
					console.log("statisticsTotalData：" + JSON.stringify(res))
					if (res) {
						_this.statisticsTotalData = res
					}
				})
			},
			//统计-图表统计
			async chartStatistics() {
				await _this.$u.api.chartStatistics({
					bookId: _this.selectBook.bookId,
					timeType: _this.sectionIndex,
					startTime: _this.startDateValue,
					endTime: _this.endDateValue,
					type: _this.type
				}).then((res) => {
					console.log("chartStatistics：" + JSON.stringify(res))
					if (res) {
						let resValue = {
							categories: res.col,
							series: [{
								data: res.data
							}]
						};
						_this.chartData = JSON.parse(JSON.stringify(resValue));
					}
				})
			},
			//统计-获取汇总列表
			async getCollectList() {
				await _this.$u.api.getCollectList({
					bookId: _this.selectBook.bookId,
					timeType: _this.sectionIndex,
					startTime: _this.startDateValue,
					endTime: _this.endDateValue
				}).then((res) => {
					console.log("getCollectListData：" + JSON.stringify(res))
					if (res) {
						_this.getCollectListData = res
						_this.statisticsCollectMoneyListRes = res.statisticsCollectMoneyListRes
					}
				})
			},
			//切换账本
			setBook(e) {
				console.log("切换账本:" + JSON.stringify(e))
				_this.selectBook = {
					bookId: e[0].value,
					bookName: e[0].label
				}
				let index = 0;
				for (let i = 0; i < _this.booksInfo.length; i++) {
					if (_this.booksInfo[i].id == e[0].value) {
						index = i;
						break
					}
				}
				_this.defaultIndex[0] = index;
				_this.ifDefaultIndex = false;
				_this.reload()
			},
			//跳转到页面关闭其他页面
			goTabbarUrl(path) {
				uni.switchTab({
					url: path
				});
			},
			//分段器选择
			sectionChange(index) {
				_this.sectionIndex = index
				if (index == 0) {
					//总
					_this.subtractEnableOrNot = false
					_this.addEnableOrNot = false
					_this.notAddEnableOrNot = false
					_this.startDateValue = ''
					_this.endDateValue = ''
					_this.changeName = '总'
					_this.isChartShow = false
				} else if (index == 1) {
					//年
					_this.subtractEnableOrNot = true
					_this.addEnableOrNot = false
					_this.notAddEnableOrNot = true
					_this.startDateValue = moment().format('YYYY')
					_this.endDateValue = ''
					_this.changeName = '年'
					_this.isChartShow = true
				} else if (index == 2) {
					//月
					_this.subtractEnableOrNot = true
					_this.addEnableOrNot = false
					_this.notAddEnableOrNot = true
					_this.startDateValue = moment().format('YYYY-MM')
					_this.endDateValue = ''
					_this.changeName = '月'
					_this.isChartShow = true
				} else {
					//周
					_this.subtractEnableOrNot = true
					_this.getWeekOfNature(new Date, 'YYYY-MM-DD')
					_this.changeName = '周'
					_this.isChartShow = true
				}
				_this.reload()
			},
			//当前时间往前推
			reduceDate() {
				if (_this.sectionIndex == 1) {
					//年
					_this.startDateValue = moment(new Date(_this.startDateValue)).subtract(1, 'years').format('YYYY')
					_this.endDateValue = ''
					_this.addEnableOrNot = true
					_this.notAddEnableOrNot = false
				} else if (_this.sectionIndex == 2) {
					//月
					_this.startDateValue = moment(new Date(_this.startDateValue)).subtract(1, 'months').format('YYYY-MM')
					_this.endDateValue = ''
					_this.addEnableOrNot = true
					_this.notAddEnableOrNot = false
				} else {
					//周
					_this.getWeekOfNature(moment(new Date(_this.startDateValue)).subtract(1, 'days'), 'YYYY-MM-DD')
				}
				_this.reload()
			},
			//当前时间往后推
			addDate() {
				if (_this.sectionIndex == 1) {
					//年
					_this.startDateValue = moment(new Date(_this.startDateValue)).add(1, 'years').format('YYYY')
					_this.endDateValue = ''
					_this.startDateValueTemp = moment().format('YYYY')
					if (_this.startDateValue === _this.startDateValueTemp) {
						_this.addEnableOrNot = false
						_this.notAddEnableOrNot = true
					} else {
						_this.addEnableOrNot = true
						_this.notAddEnableOrNot = false
					}
				} else if (_this.sectionIndex == 2) {
					//月
					_this.startDateValue = moment(new Date(_this.startDateValue)).add(1, 'months').format('YYYY-MM')
					_this.endDateValue = ''
					_this.startDateValueTemp = moment().format('YYYY-MM')
					if (_this.startDateValue === _this.startDateValueTemp) {
						_this.addEnableOrNot = false
						_this.notAddEnableOrNot = true
					} else {
						_this.addEnableOrNot = true
						_this.notAddEnableOrNot = false
					}
				} else {
					//周
					_this.getWeekOfNature(moment(new Date(_this.endDateValue)).add(1, 'days'), 'YYYY-MM-DD')
				}
				_this.reload()
			},
			//计算周开始时间和结束时间
			getWeekOfNature(date, format) {
				let weekOfday = moment(date).format("E"); //计算是这周第几天
				let monday = moment(date).subtract(weekOfday - 1, "days"); //获取周一
				let sunday = moment(date).add(7 - weekOfday, "days"); // 获取周日
				if (moment().format(format) >= monday.format(format) && moment().format(format) <= sunday.format(format)) {
					_this.addEnableOrNot = false
					_this.notAddEnableOrNot = true
				} else {
					_this.addEnableOrNot = true
					_this.notAddEnableOrNot = false
				}
				_this.startDateValue = format ? monday.format(format) : monday;
				_this.endDateValue = format ? sunday.format(format) : sunday;
			},
			//打开日历
			selectDate() {
				_this.showDate = true
			},
			//日期选择
			change(e) {
				console.log(e);
				_this.subtractEnableOrNot = false
				_this.addEnableOrNot = false
				_this.notAddEnableOrNot = false
				_this.startDateValue = e.startDate
				_this.endDateValue = e.endDate
				_this.sectionIndex = 2
				_this.isChartShow = true
				_this.reload()
			},
			//切换折线图
			toggleColumn() {
				_this.isEnableOrNotAreaCharts = false
				_this.isEnableOrNotColumnCharts = true
				_this.chartStatistics();
			},
			//切换柱状图
			toggleArea() {
				_this.isEnableOrNotAreaCharts = true
				_this.isEnableOrNotColumnCharts = false
				_this.chartStatistics();
			},
			//切换收入支出
			toggleChange(index) {
				_this.type = index
				if (index == 0) {
					_this.incOrExpName = '收入'
				} else {
					_this.incOrExpName = '支出'
				}
				_this.chartStatistics();
			}
		}
	}
</script>

<style scoped lang="scss">
	.sticky {
		background-color: #ffffff;
		color: #000000;
		padding: 20rpx;
	}

	.body {
		background-color: $u-bg-color;
	}

	.subsection-style {
		/* 设置视图的宽度 */
		width: 200px;
	}

	.toggle-subsection-style {
		/* 设置视图的宽度 */
		width: 80px;
	}

	.u-bg {
		background-image: linear-gradient(45deg, #ffffff, #ffffff);
		color: #000000;
		border-radius: 12px;
		border: 1rpx solid #ebeef5;
	}

	/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
	.charts-box {
		width: 100%;
		height: 150px;
	}
</style>